
// ============================== 01.打开图片消息页面 ==============================
// 01.点击图文消息
// await page.locator(selectors.articleMessage).click();
await page
    .locator("div.weui-desktop-panel__bd > div > div:nth-child(2)")
    .click();

// 02.接收新页面
const newPage = await context.waitForEvent("page");
console.log("跳转到图文消息编辑页面成功!");
// 等待网络加载结束
await newPage.waitForLoadState("networkidle");

// ============================== 02.黏贴html文件 ==============================
try {
    // console.log('sendData.htmlPath:', sendData.htmlPath);
    // 如果不存在,则不执行黏贴
    if (sendData.htmlPath) {
        const htmlContent = fs.readFileSync(sendData.htmlPath, "utf8");
        // console.log('htmlContent:', htmlContent);
        // 粘贴到编辑器
        const editorSelector = "#ueditor_0 > div > div > div > div";
        await newPage.waitForSelector(editorSelector, {
            state: "attached",
            timeout: 60000,
        });
        await newPage.locator(editorSelector).click();

        // 修改 editorSelector 的innerHTML
        await newPage.evaluate(
            ({ editorSelector, htmlContent }) => {
                const editor = document.querySelector(editorSelector);
                editor.innerHTML = htmlContent;
            },
            { editorSelector, htmlContent }
        );
        console.log("黏贴 html 成功!");
    } else {
        console.log("html文件不存在,不执行黏贴!");
    }
} catch (error) {
    console.error("粘贴内容失败:", error);
}

// 等待2秒
await new Promise((resolve) => setTimeout(resolve, 1000));

// ============================== 03.设置音频 ==============================
if (sendData.audioPath) {
    console.log("设置音频!");
    // 点击音频
    await newPage.locator("#audio_music_plugin_btn").click();
    console.log("点击音频菜单成功!");
    // 等待2秒
    await new Promise((resolve) => setTimeout(resolve, 1000));
    // 点击音频选项
    await newPage
        .locator(
            "#audio_music_plugin_btn > ul > li.tpl_dropdown_menu_item.js_insertaudio"
        )
        .click();
    console.log("点击音频选项成功!");
    // 等待2秒
    await new Promise((resolve) => setTimeout(resolve, 1000));
    // 点击上传按钮
    await newPage
        .locator("div.weui-desktop-btn_wrp > button")
        .first()
        .click();
    console.log("点击上传按钮成功!");
    // 等待2秒
    await new Promise((resolve) => setTimeout(resolve, 2000));
    // 上传音频文件 #ftnUpload_
    await newPage
        .locator('input[ id ^= "ftnUpload"]')
        .setInputFiles(sendData.audioPath);
    console.log("上传音频文件成功!");
    // 等待2秒
    await new Promise((resolve) => setTimeout(resolve, 2000));
    // 点击确认协议
    await newPage
        .locator("div.audio-upload-dialog_agreement > div > label > i")
        .click();
    console.log("点击确认协议成功!");
    // 等待2秒
    await new Promise((resolve) => setTimeout(resolve, 2000));

    // 点击保存按钮
    await newPage
        .locator("div.weui-desktop-dialog__ft > div > div > button")
        .first()
        .click();
    console.log("点击保存按钮成功!");
    // 等待2秒
    await new Promise((resolve) => setTimeout(resolve, 2000));

    // 点击第一个音频
    await newPage.locator("div.audio_item_wrp > label").first().click();
    console.log("点击第一个音频成功!");
    // 等待2秒
    await new Promise((resolve) => setTimeout(resolve, 2000));
    // 点击插入 按钮
    await newPage
        .locator(" div.weui-desktop-dialog__ft > div:nth-child(3) > button")
        .click();
    console.log("点击插入按钮成功!");
}

// 等待2秒
await new Promise((resolve) => setTimeout(resolve, 2000));

// ============================== 04.设置标题、作者、描述 ==============================
// 输入标题
await newPage.locator("#title").fill(sendData?.title || "");
console.log("输入标题成功!");
// 输入作者
await newPage.locator("#author").fill(sendData?.author || "");
console.log("输入作者成功!");

// 输入描述
await newPage.locator("#js_description").fill(sendData?.description || "");
console.log("输入描述成功!");

// ============================== 03.上传封面图片 ==============================
// 上传封面图片
// 滚动到这个区域
await newPage.locator("#js_cover_area").scrollIntoViewIfNeeded();
//悬停在这个区域,然后等待列表出现,再点击
await newPage.locator("#js_cover_area").hover();
// 等待列表出现
await new Promise((resolve) => setTimeout(resolve, 1000));
// 点击封面图片
await newPage.locator("#js_cover_null > ul > li:nth-child(2) > a").click();

// 等待2秒
await new Promise((resolve) => setTimeout(resolve, 2000));

// 点击上传按钮 上传图片
await newPage
    .locator('div[ id ^= "rt_rt_"] > input[type=file]')
    .setInputFiles(sendData.coverPath);

// 等待网络请求结束
await newPage.waitForLoadState("networkidle");
await new Promise((resolve) => setTimeout(resolve, 2000));
// 上传成功默认会出现这个选择器 :#js_image_dialog_list_wrp > div > div.weui-desktop-img-picker__item.selected
await newPage
    .locator(
        "#js_image_dialog_list_wrp > div > div.weui-desktop-img-picker__item.selected"
    )
    .waitFor();
console.log("上传封面图片成功!");
await new Promise((resolve) => setTimeout(resolve, 1000));
// 点击下一步按钮 div.weui-desktop-dialog__ft > div:nth-child(1) > button
await newPage
    .locator("div.weui-desktop-dialog__ft > div:nth-child(1) > button")
    .click();
console.log("点击下一步按钮成功!");
await new Promise((resolve) => setTimeout(resolve, 1000));
// 点击确认 div.weui-desktop-dialog__ft > div:nth-child(2) > button
await newPage
    .locator("div.weui-desktop-dialog__ft > div:nth-child(2) > button")
    .click();
console.log("点击确认按钮成功!");

// 等待 2 秒
await new Promise((resolve) => setTimeout(resolve, 3000));

// ============================== 04.设置原创 ==============================

if (sendData.isOriginal) {
    console.log("设置原创!");
    // 点击原创
    await newPage.locator("#js_original > div").first().click();
    console.log("点击原创按钮成功!");
    // 等待1秒
    await new Promise((resolve) => setTimeout(resolve, 1000));
    // 点击 .weui-desktop-icon-checkbox
    await newPage.locator(".weui-desktop-icon-checkbox").click();
    console.log("点击同意协议选项!");
    // 点击确认按钮
    await newPage
        .locator(
            " div > div.weui-desktop-dialog__ft > div > div:nth-child(2) > button"
        )
        .first()
        .click();
    console.log("点击确认按钮成功!");
    await new Promise((resolve) => setTimeout(resolve, 1000));
}

// ============================== 05.设置赞赏 ==============================
if (sendData.isReward) {
    console.log("设置赞赏!");
    // 点击赞赏
    await newPage.locator("#js_reward_setting_area > div").click();
    console.log("点击赞赏区域成功!等待加载，请不要操作···");
    // 等待1秒
    await new Promise((resolve) => setTimeout(resolve, 2000));
    // 点击赞赏按钮
    await newPage
        .locator("div.operate-btn__group > div:nth-child(1) > button")
        .first()
        .click();
    console.log("确认赞赏按钮成功!");
    // 等待1秒
    await new Promise((resolve) => setTimeout(resolve, 1000));
}

// ============================== 06.设置合集 ==============================
// 如果合集不为空
if (sendData.tagList.length > 0) {
    console.log("设置合集!");
    // 点击合集
    await newPage.locator("#js_article_tags_area > label > div").click();
    console.log("点击合集成功!");
    // 等待1秒
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 点击输入合集区域
    await newPage.locator('input[placeholder="请选择合集"]').click();
    // 2025年7月27日 公众号修改了规则，加载已有的合集，时间会比较长，要等待
    await new Promise((resolve) => setTimeout(resolve, 3000));
    // 输入内容
    // 优化：循环处理tagList
    for (const tag of sendData.tagList) {
        await newPage.locator('input[placeholder="请选择合集"]').fill(tag);
        await newPage.keyboard.press("Enter");
        await new Promise((resolve) => setTimeout(resolve, 500)); // 添加适当延迟

        // 2025年7月27日 公众号修改了规则，只允许一个合集

        break;
    }
    // 点击确定按钮
    await newPage
        .locator("div.weui-desktop-dialog__ft > div:nth-child(1) > button")
        .first()
        .click();
    console.log("输入合集内容成功!");
    await new Promise((resolve) => setTimeout(resolve, 1000));
}

// ============================== 07.设置创作声明 ==============================

console.log("设置创作声明!");
// 获取页面尺寸并计算中间位置
const viewportSize = await newPage.evaluate(() => {
    return {
        width: window.innerWidth,
        height: window.innerHeight,
    };
});
const centerX = Math.floor(viewportSize.width / 2);
const centerY = Math.floor(viewportSize.height / 2);

// 将鼠标移动到页面中心位置
await newPage.mouse.move(centerX, centerY);
await new Promise((resolve) => setTimeout(resolve, 1000));

// 点击创作声明区域
await newPage.locator("#js_claim_source_area > label > div").click();
await new Promise((resolve) => setTimeout(resolve, 1000));
// 点击含有 素材来源于官方 文本的span
await newPage
    .locator(
        "div.popover.popover_article_claim_source.pos_down_center.pos_center > div > div > div > div > div > div:nth-child(2) > label"
    )
    .click();
console.log("点击创作声明成功!");
await new Promise((resolve) => setTimeout(resolve, 1000));

// ============================== 08.设置原文链接 ==============================
if (sendData.originalUrl) {
    await newPage.locator("#js_article_url_area > label > div > i").click();
    // 等待2秒
    await new Promise((resolve) => setTimeout(resolve, 1000));
    // 输入原文链接
    await newPage
        .locator('input[placeholder="输入或粘贴原文链接"]')
        .fill(sendData.originalUrl);
    // 等待1秒
    await new Promise((resolve) => setTimeout(resolve, 1000));
    // 按下回车
    await newPage.keyboard.press("Enter");
    console.log("设置原文链接成功!");
}

// ============================== 10.设置预览 ==============================

try {
    // 等待3秒
    await new Promise((resolve) => setTimeout(resolve, 3000));
    // 点击预览
    await newPage.locator("#js_preview > button").click();
    // 等待3秒
    await new Promise((resolve) => setTimeout(resolve, 3000));

    // 等待预览弹窗出现
    await newPage.waitForSelector("div.dialog_hd > h3", { state: "visible" });
    console.log("预览弹窗已出现");
    // 获取缓存的预览容器数量
    const containerCount = await newPage
        .locator("#js_preview_wxname_container > span > a")
        .count();

    if (containerCount > 0) {
        console.log("缓存的预览微信名称数量:", containerCount);
        // 循环点击清除缓存的预览微信名称
        for (let i = 0; i < containerCount; i++) {
            // 使用nth(i)来逐个处理每个元素
            const previewItem = newPage
                .locator("#js_preview_wxname_container > span > a")
                .first();
            await previewItem.waitFor({ state: "visible" });
            await previewItem.click();
            await new Promise((resolve) => setTimeout(resolve, 500)); // 添加短暂等待
        }
        console.log("清除缓存的预览微信名称成功!");
    }

    // 程序等待 1 秒
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 输入预览的微信名
    await newPage.locator("#js_preview_wxname").fill(sendData.previewName);
    // 按下回车
    await newPage.keyboard.press("Enter");
    console.log("预览的微信名输入成功!");

    // 程序等待 1 秒
    await new Promise((resolve) => setTimeout(resolve, 3000));
    // 点击确定
    await newPage
        .locator("span.btn.btn_primary.btn_input.js_btn_p > button")
        .click();
    console.log("发送预览成功!");

    return true;
} catch (error) {
    console.error("设置预览失败:", error);
    return false;
}